package com.example.demo.Util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;
@Component
public class RedisUtli {
    @Autowired
    private  RedisTemplate<String, Object> redisTemplate;
    // 生成唯一ID
    public Integer generateId(String prefix) {
        // 获取当前时间戳（精确到天）
        long days = System.currentTimeMillis() / (24 * 60 * 60 * 1000);
        // 构造Redis key，按天区分
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String dateStr = sdf.format(new Date());
        String redisKey = prefix + ":id:" + dateStr;
        // 获取当日自增序列
        Long sequence = redisTemplate.opsForValue().increment(redisKey);
        // 设置当天过期，第二天自动重置序列
        if (sequence == 1) {
            // 计算今日剩余秒数
            long expireSeconds = calculateTodayRemainSeconds();
            redisTemplate.expire(redisKey, expireSeconds, TimeUnit.SECONDS);
        }
        // 格式化返回：前缀_时间戳_序列号
        String idStr = String.format("%06d%04d", days% 10000, sequence % 10000);
        return Integer.parseInt(idStr);
    }
    /**
     * 计算今日剩余秒数
     */
    private  long calculateTodayRemainSeconds() {
        long now = System.currentTimeMillis();
        long endOfDay = ((now / 86400000) + 1) * 86400000 - TimeZone.getDefault().getRawOffset();
        return (endOfDay - now) / 1000;
    }
}
